import numpy as np
import matplotlib.pyplot as plt
#支持中文
plt.rcParams['font.family'] = ['sans-serif']
plt.rcParams['font.sans-serif'] = ['SimHei']
# 准备数据
categories = ['苹果', '香蕉', '橙子', '葡萄']
sales_2022 = [45, 30, 25, 40]
sales_2023 = [52, 28, 32, 38]
# 设置样式
x = np.arange(len(categories))
width = 0.35
fig, ax = plt.subplots(figsize=(8,5))
# 绘制柱状图
rects1 = ax.bar(x - width/2, sales_2022, width, label='2022', color='#4ECDC4')
rects2 = ax.bar(x + width/2, sales_2023, width, label='2023', color='#FF6B6B')
# 设置x轴刻度和标签
ax.set_xticks(x)
ax.set_xticklabels(categories)
ax.legend()


# 添加数据标签
def autolabel(rects):
    for rect in rects:
        height = rect.get_height()
        ax.annotate(f'{height}',
                    xy=(rect.get_x() + rect.get_width()/2, height),
                    xytext=(0, 3),
                    textcoords="offset points",
                    ha='center', va='bottom')


autolabel(rects1)
autolabel(rects2)


plt.title("水果销量年度对比")
plt.show()
